package com.github.shiqiyue.app.config.session;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.web.util.matcher.AndRequestMatcher;
import org.springframework.session.web.http.CookieHttpSessionIdResolver;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/****
 * httpSession策略，同时支持cookie和header
 *
 * @author wwy
 *
 */
@Slf4j
public class CookieAndHeaderHttpSessionIdResolver implements UrlMatchHttpSessionIdResolver {

    private CookieHttpSessionIdResolver cookieHttpSessionIdResolver;

    private HeaderHttpSessionIdResolver headerHttpSessionIdResolver;

    private String urlPrefix;

    public CookieAndHeaderHttpSessionIdResolver(CookieHttpSessionIdResolver cookieHttpSessionIdResolver, HeaderHttpSessionIdResolver headerHttpSessionIdResolver, String urlPrefix) {
        this.cookieHttpSessionIdResolver = cookieHttpSessionIdResolver;
        this.headerHttpSessionIdResolver = headerHttpSessionIdResolver;
        this.urlPrefix = urlPrefix;
    }

    @Override
    public boolean match(String servletPath) {
        if (servletPath.startsWith(urlPrefix)) {
            return true;
        }
        return false;
    }


    @Override
    public List<String> resolveSessionIds(HttpServletRequest request) {
        // cookie part
        List<String> sessionIds = cookieHttpSessionIdResolver.resolveSessionIds(request);
        if (sessionIds != null && !sessionIds.isEmpty()) {
            return sessionIds;
        }
        // header part
        sessionIds = headerHttpSessionIdResolver.resolveSessionIds(request);
        if (sessionIds != null && !sessionIds.isEmpty()) {
            return sessionIds;
        }
        return new ArrayList<>();
    }

    @Override
    public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {
        headerHttpSessionIdResolver.setSessionId(request, response, sessionId);
        cookieHttpSessionIdResolver.setSessionId(request, response, sessionId);
    }

    @Override
    public void expireSession(HttpServletRequest request, HttpServletResponse response) {
        headerHttpSessionIdResolver.expireSession(request, response);
        cookieHttpSessionIdResolver.expireSession(request, response);
    }


}
